package com.woody.aggregate.application.service.shop.es.impl;

import com.woody.aggregate.application.service.shop.es.EsShopQueryService;
import com.woody.aggregate.common.consts.es.AiShopIndexIdPrefix;
import com.woody.aggregate.domain.saas.SaasShopIndustryManager;
import com.woody.aggregate.infrastructure.saas.entity.SaasShopIndustry;
import com.woody.aggregate.infrastructure.shop.es.esdoc.ShopInfo;
import com.woody.aggregate.infrastructure.shop.es.esmapper.ShopInfoEsMapper;
import com.woody.aggregate.saas.enums.SaasShopIndustryLevenEnum;
import com.woody.aggregate.shop.enums.es.EsShopListDisplayType;
import com.woody.aggregate.shop.enums.es.EsShopTypeEnum;
import com.woody.aggregate.shop.req.es.EsVipShopListRequest;
import com.woody.aggregate.shop.req.es.QueryEsShopByIdsRequest;
import com.woody.aggregate.shop.vo.ESPageInfo;
import com.woody.aggregate.shop.vo.EsShopInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dromara.easyes.core.biz.SAPageInfo;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * ES门店查询服务实现类
 *
 * @author wénkǎi.zhāng
 */
@Service
@Slf4j
public class EsShopQueryServiceImpl implements EsShopQueryService {

    @Autowired
    private ShopInfoEsMapper shopInfoEsMapper;

    @Autowired
    private SaasShopIndustryManager saasShopIndustryManager;

    @Override
    public List<EsShopInfoVo> queryByIds(QueryEsShopByIdsRequest request) {
        if (CollectionUtils.isEmpty(request.getShopIds())) {
            return new ArrayList<>();
        }

        log.info("根据门店ID批量查询门店信息, shopIds={}", request.getShopIds());

        // 将门店ID转换为ES文档ID
        List<String> esIds = request.getShopIds().stream()
                .map(AiShopIndexIdPrefix::getShopIndexId)
                .collect(Collectors.toList());

        // 查询ES
        List<ShopInfo> shopInfoList = shopInfoEsMapper.selectBatchIds(esIds);

        if (CollectionUtils.isEmpty(shopInfoList)) {
            return new ArrayList<>();
        }

        // 转换为VO
        return shopInfoList.stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());
    }

    @Override
    public ESPageInfo<EsShopInfoVo> vipShopList(EsVipShopListRequest request) {
        log.info("查询精选门店列表, request={}", request);

        // 构建ES查询条件
        LambdaEsQueryWrapper<ShopInfo> wrapper = new LambdaEsQueryWrapper<>();

        // 筛选条件：精选门店 = "非普通门店" + "列表显示"
        wrapper.in(ShopInfo::getShopType, Arrays.asList(EsShopTypeEnum.MAIN.getType(), EsShopTypeEnum.CHILD.getType(), EsShopTypeEnum.BD.getType()))
                .eq(ShopInfo::getDisplayType, EsShopListDisplayType.LIST.getType())
                .eq(ShopInfo::getShopStatus, "OPEN");

        // 根据省市区筛选 - 优先级：区 > 市 > 省
        if (StringUtils.isNotBlank(request.getAreaCode())) {
            wrapper.eq(ShopInfo::getAreaId, request.getAreaCode());
        } else if (StringUtils.isNotBlank(request.getCityCode())) {
            wrapper.eq(ShopInfo::getCityId, request.getCityCode());
        } else if (StringUtils.isNotBlank(request.getProvinceCode())) {
            wrapper.eq(ShopInfo::getProvinceId, request.getProvinceCode());
        }

        // 行业筛选
        if (request.getShopIndustryCode() != null) {
            // 查询该一级行业下的所有三级行业编号
            List<SaasShopIndustry> industryList = saasShopIndustryManager.likeRightByCode(request.getShopIndustryCode());
            Set<Long> industryCodes  = industryList.stream().filter(o -> SaasShopIndustryLevenEnum.LV_LAST.getLevel().equals(o.getLevel())).map(SaasShopIndustry::getCode).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(industryList)) {
                wrapper.in(ShopInfo::getSaasIndustryCode, industryCodes);
            }
        }

        // 地理位置搜索
        if (request.getLatitude() != null && request.getLongitude() != null && request.getDistanceLimit() != null) {
            // 经纬度查询
            String geoPoint = request.getLatitude() + "," + request.getLongitude();
            wrapper.geoDistance(ShopInfo::getShopLatLng, geoPoint, request.getDistanceLimit() + "km");
            // 按距离排序
            wrapper.orderByAsc(ShopInfo::getDistance);
        } else {
            // 默认排序
            wrapper.orderByDesc(ShopInfo::getGrade);
        }

        // search_after翻页查询
        wrapper.size(request.getSize());
        SAPageInfo<ShopInfo> saPageInfo = shopInfoEsMapper.searchAfterPage(wrapper, request.getSearchAfter(), request.getSize());

        // 转换为ESPageInfo
        ESPageInfo<EsShopInfoVo> result = new ESPageInfo<>();
        result.setPageSize(saPageInfo.getPageSize());
        result.setPages(saPageInfo.getPages());

        // 设置searchAfter和nextSearchAfter
        result.setSearchAfter((List)saPageInfo.getSearchAfter());
        result.setNextSearchAfter((List)saPageInfo.getNextSearchAfter());

        // 转换门店信息
        List<EsShopInfoVo> shopInfoVoList = saPageInfo.getList().stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());

        result.setList(shopInfoVoList);

        return result;
    }

    /**
     * 将ES门店信息转换为VO
     *
     * @param shopInfo ES门店信息
     * @return 门店信息VO
     */
    private EsShopInfoVo convertToVo(ShopInfo shopInfo) {
        EsShopInfoVo vo = new EsShopInfoVo();

        vo.setShopId(shopInfo.getShopId());
        vo.setShopName(shopInfo.getShopName());
        vo.setProvinceId(shopInfo.getProvinceId());
        vo.setCityId(shopInfo.getCityId());
        vo.setAreaId(shopInfo.getAreaId());
        vo.setProvince(shopInfo.getProvince());
        vo.setCity(shopInfo.getCity());
        vo.setArea(shopInfo.getArea());
        vo.setShopAddress(shopInfo.getShopAddress());
        vo.setSaasIndustryCode(shopInfo.getSaasIndustryCode());
        vo.setIndustryCode(shopInfo.getIndustryCode());

        // 门头图URL列表
        if (StringUtils.isNotBlank(shopInfo.getFacadePicUrls())) {
            vo.setFacadePicUrls(Arrays.asList(shopInfo.getFacadePicUrls().split(",")));
        }

        // 详情图URL列表
        if (StringUtils.isNotBlank(shopInfo.getDetailPicUrls())) {
            vo.setDetailPicUrls(Arrays.asList(shopInfo.getDetailPicUrls().split(",")));
        }

        vo.setShopLogoUrl(shopInfo.getShopLogoUrl());
        vo.setShopLatLon(shopInfo.getShopLatLng());
        vo.setShopStatus(shopInfo.getShopStatus());
        vo.setGrade(shopInfo.getGrade());
        vo.setSales(shopInfo.getSales());
        vo.setQualityRate(shopInfo.getQualityRate());
        vo.setShopType(shopInfo.getShopType());
        vo.setAuthBeginTime(shopInfo.getAuthBeginTime());
        vo.setAuthEndTime(shopInfo.getAuthEndTime());

        return vo;
    }
}
